# -*- coding: utf-8 -*-
# @Date   : 2020/2/5
# @File   : AC13_Past3MonsAddedTinyCompLoanCnt_Change_Value.py
# @Author : zhaochen
'''eof
name:近3个月新增小额贷款公司贷款笔数_change_value
code:AC13_Past3MonsAddedTinyCompLoanCnt_Change_Value
tableName:
columnName:
groups:AC模块
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import json
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def isFloat(x):
    '''
    判断x为float类型且大于等于0
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def getRatingInfoData(code, interface=None, last=False):
    '''
    获取上次评级信息的指标值或接口数据，默认返回的格式是tuple(val, "value") 指标值和标记
    标记分为 'value':指标值 'data':数据
    :param code: 要获取的指标值的指标code
    :param interface: EC_DSJ_2D/IC_DSJ_2D/TX_CQ_DSJ
    :return:
    '''
    try:
        historyRatingInfo = json.loads(ratingRequest.get("historyRatingInfo"))
        if last:
            # 获取上次评级数据信息
            ratingInfo = historyRatingInfo.get("lastRatingInfo")
        else:
            # 获取本次评级数据
            ratingInfo = historyRatingInfo.get("ratingInfo")
        # 如果是取score 或者 ratingLevel 直接返回
        if code in ["score", "ratingLevel"]:
            score = ratingInfo.get(code)
            try:
                return float(score), "value"
            except:
                return None, None
        # 取数据类型进行判断
        dataType = ratingInfo.get("dataType")
        # 如果传回来是数据 则返回相应接口里面的数据data
        if dataType == "1":
            data = ratingInfo.get(interface).get("data")
            if isinstance(data, dict):
                return (data, "data")
            else:
                return None, None
        # 如果传回来是指标值，则通过code进行提取
        elif dataType == "2":
            val = ratingInfo.get(code)
            if val in null_type_list:
                return None, None
            else:
                try:
                    return float(val), "value"
                except:
                    return None, None
        else:
            return None, None
    except:
        return None, None

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def dateFormat(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None
#上次评级时间
lastGmtCreateTime=dateFormat(ratingRequest.get("lastGmtCreateTime"))

def past3MonsAddedTinyCompLoanCnt2D(data,RatingTime):
    # 借贷账户信息
    PDA = getTable(data, 'PDA', 1)
    if PDA is None:
        return None
    elif PDA == "":
        return 0
    else:
        # 借贷账户信息单元
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return None
        elif PD01 == [{}]:
            return 0
        else:
            factor = []
            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1)
                    if PD01A is None or PD01A == "":
                        factor.append(None)
                    else:
                        # 开立日期   [1..1]
                        PD01AR01 = PD01A[0].get('PD01AR01')
                        # 业务管理机构类型   [1..1]
                        PD01AD02 = PD01A[0].get('PD01AD02')
                        if dateFormat(PD01AR01) in null_type_list or PD01AD02 in null_type_list:
                            factor.append(None)
                        else:
                            # 51-小额贷款公司
                            if PD01AD02 == '51':
                                threeMonthAgo = RatingTime - datetime.timedelta(days=3*30)
                                PD01AR01 = dateFormat(PD01AR01)
                                if PD01AR01 > threeMonthAgo:
                                    factor.append(1)
                                else:
                                    factor.append(0)
                            else:
                                factor.append(0)
                except:
                    factor.append(None)
                    continue

    factor = filter(lambda x: x is not None, factor)
    if len(factor) == 0:
        return None
    else:
        return sum(factor)

def getTable1d(data, table_Name):
    try:

        data = data.get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}] #ReportNo EC是大写 IC 是reportNo 小写
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def past3MonsAddedTinyCompLoanCnt1D(data,RatingTime):
    try:
        # three_month_ago = (datetime.datetime.now() - relativedelta(months=3)).strftime("%Y%m%d")
        three_month_ago = (RatingTime - datetime.timedelta(days=3*30))
        ICRLoanInfo002Loan = getTable1d(data, 'ICRLoanInfo002*Loan')

        if ICRLoanInfo002Loan is None:
            return None
        elif ICRLoanInfo002Loan == [{}]:
            return 0
        else:
            flag = []
            count = 0
            for i in ICRLoanInfo002Loan:
                financeType = i.get('financeType')
                openDate = i.get('openDate')

                if financeType in null_type_list or openDate in null_type_list or dateFormat(openDate) is None:
                    flag.append(None)
                    continue
                else:
                    if financeType == u'小额信贷公司' and dateFormat(openDate) > three_month_ago:
                        count += 1
                    else:
                        pass
            if len(flag) == len(ICRLoanInfo002Loan):
                return None
            else:
                return count
    except:
        return None


def factor1():
    data, data_type = getRatingInfoData('past3MonsAddedTinyCompLoanCnt2D', interface='IC_DSJ_2D', last=False)
    if data_type == 'value':
        try:
            return float(data)
        except:
            return None
    elif data_type == 'data':
        res = past3MonsAddedTinyCompLoanCnt2D(data,RatingTime=datetime.datetime.now())
        return res
    else:
        return None

def factor2():
    data, data_type = getRatingInfoData('past3MonsAddedTinyCompLoanCnt1D', interface='IC_DSJ', last=True)
    if data is None:
        # 如果一代的数据没有，则使用二代的数据去取
        data, data_type = getRatingInfoData('past3MonsAddedTinyCompLoanCnt2D', interface='IC_DSJ_2D', last=True)
        if data_type == 'value':
            try:
                return float(data)
            except:
                return None
        elif data_type == 'data':
            res = past3MonsAddedTinyCompLoanCnt2D(data,RatingTime=lastGmtCreateTime)
            return res
        else:
            return None
    else:
        if data_type == 'value':
            try:
                return float(data)
            except:
                return None
        elif data_type == 'data':
            res = past3MonsAddedTinyCompLoanCnt1D(data,RatingTime=lastGmtCreateTime)
            return res
        else:
            return None

def AC13_Past3MonsAddedTinyCompLoanCnt_Change_Value():
    f1 = factor1()
    f2 = factor2()
    if f1 is None or f2 is None:
        return u'缺失值'
    else:
        return f1 - f2


result = AC13_Past3MonsAddedTinyCompLoanCnt_Change_Value()
